package com.campus.help.controller.admin;

import com.campus.help.common.Result;
import com.campus.help.dto.AdminLoginDTO;
import com.campus.help.entity.Admin;
import com.campus.help.service.AdminService;
import com.campus.help.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 管理员控制器
 */
@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public Result login(@Valid @RequestBody AdminLoginDTO loginDTO) {
        log.info("管理员登录: {}", loginDTO.getUsername());

        try {
            return adminService.login(loginDTO);
        } catch (Exception e) {
            log.error("管理员登录异常", e);
            return Result.error("登录失败，请稍后重试");
        }
    }

    /**
     * 获取当前管理员信息
     */
    @GetMapping("/info")
    public Result getAdminInfo(HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未登录或token无效");
            }

            // 验证token并获取管理员信息
            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            if (tokenInfo == null) {
                return Result.error(401, "token已过期或无效");
            }

            // 根据token中的管理员ID获取管理员信息
            Long adminId = tokenInfo.getAdminId();
            Admin admin = adminService.getById(adminId);

            if (admin == null) {
                return Result.error(404, "管理员不存在");
            }

            // 返回管理员信息（脱敏）
            return Result.success(buildAdminInfo(admin));

        } catch (Exception e) {
            log.error("获取管理员信息异常", e);
            return Result.error("获取信息失败");
        }
    }

    /**
     * 管理员退出登录
     */
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            log.info("管理员退出登录, token: {}", token != null ? "有效" : "无效");

            // 这里可以将token加入黑名单，暂时简单返回成功
            return Result.success("退出登录成功");

        } catch (Exception e) {
            log.error("管理员退出登录异常", e);
            return Result.error("退出登录失败");
        }
    }

    /**
     * 修改密码
     */
    @PostMapping("/changePassword")
    public Result changePassword(@RequestBody Map<String, String> params, HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未登录或token无效");
            }

            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            if (tokenInfo == null) {
                return Result.error(401, "token已过期或无效");
            }

            String oldPassword = params.get("oldPassword");
            String newPassword = params.get("newPassword");

            if (oldPassword == null || newPassword == null) {
                return Result.error(400, "旧密码和新密码不能为空");
            }

            if (newPassword.length() < 6) {
                return Result.error(400, "新密码长度不能少于6位");
            }

            Long adminId = tokenInfo.getAdminId();
            Admin admin = adminService.getById(adminId);
            
            if (admin == null) {
                return Result.error(404, "管理员不存在");
            }

            // 验证旧密码
            String encryptedOldPassword = encryptPassword(oldPassword);
            if (!encryptedOldPassword.equals(admin.getPassword())) {
                return Result.error(400, "旧密码错误");
            }

            // 更新密码
            String encryptedNewPassword = encryptPassword(newPassword);
            boolean success = adminService.updatePassword(adminId, encryptedNewPassword);
            
            if (success) {
                log.info("管理员修改密码成功: adminId={}", adminId);
                return Result.success("密码修改成功");
            } else {
                return Result.error("密码修改失败");
            }

        } catch (Exception e) {
            log.error("修改密码异常", e);
            return Result.error("修改密码失败");
        }
    }

    /**
     * 获取系统统计信息
     */
    @GetMapping("/stats")
    public Result getStats(HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未登录或token无效");
            }

            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            if (tokenInfo == null) {
                return Result.error(401, "token已过期或无效");
            }

            // 获取系统统计信息
            Map<String, Object> stats = adminService.getSystemStats();

            return Result.success(stats);

        } catch (Exception e) {
            log.error("获取统计信息异常", e);
            return Result.error("获取统计信息失败");
        }
    }

    /**
     * 从请求中获取token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        return null;
    }

    /**
     * 构建管理员信息（脱敏）
     */
    private Map<String, Object> buildAdminInfo(Admin admin) {
        Map<String, Object> adminInfo = new HashMap<>();
        adminInfo.put("id", admin.getId());
        adminInfo.put("username", admin.getUsername());
        adminInfo.put("name", admin.getName() != null ? admin.getName() : "");
        adminInfo.put("email", admin.getEmail() != null ? admin.getEmail() : "");
        adminInfo.put("phone", admin.getPhone() != null ? admin.getPhone() : "");
        adminInfo.put("role", admin.getRole());
        adminInfo.put("status", admin.getStatus());
        adminInfo.put("lastLoginTime", admin.getLastLoginTime());
        return adminInfo;
    }

    /**
     * 获取管理员列表
     */
    @GetMapping("/list")
    public Result getAdminList(@RequestParam(defaultValue = "1") int page,
                              @RequestParam(defaultValue = "10") int size,
                              @RequestParam(required = false) String keyword,
                              @RequestParam(required = false) Integer role,
                              @RequestParam(required = false) Integer status,
                              HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未登录或token无效");
            }

            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            if (tokenInfo == null) {
                return Result.error(401, "token已过期或无效");
            }

            // 检查权限（只有超级管理员可以查看管理员列表）
            if (tokenInfo.getRole() != 1) {
                return Result.error(403, "权限不足");
            }

            Map<String, Object> result = adminService.getAdminList(page, size, keyword, role, status);
            return Result.success(result);

        } catch (Exception e) {
            log.error("获取管理员列表异常", e);
            return Result.error("获取管理员列表失败");
        }
    }

    /**
     * 更新管理员状态
     */
    @PostMapping("/updateStatus")
    public Result updateAdminStatus(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未登录或token无效");
            }

            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            if (tokenInfo == null) {
                return Result.error(401, "token已过期或无效");
            }

            // 检查权限（只有超级管理员可以更新状态）
            if (tokenInfo.getRole() != 1) {
                return Result.error(403, "权限不足");
            }

            Long adminId = Long.valueOf(params.get("adminId").toString());
            Integer status = Integer.valueOf(params.get("status").toString());

            // 不能禁用自己
            if (adminId.equals(tokenInfo.getAdminId())) {
                return Result.error(400, "不能修改自己的状态");
            }

            boolean success = adminService.updateAdminStatus(adminId, status, tokenInfo.getAdminId());
            if (success) {
                return Result.success("状态更新成功");
            } else {
                return Result.error("状态更新失败");
            }

        } catch (Exception e) {
            log.error("更新管理员状态异常", e);
            return Result.error("更新管理员状态失败");
        }
    }

    /**
     * 重置管理员密码
     */
    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未登录或token无效");
            }

            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            if (tokenInfo == null) {
                return Result.error(401, "token已过期或无效");
            }

            // 检查权限（只有超级管理员可以重置密码）
            if (tokenInfo.getRole() != 1) {
                return Result.error(403, "权限不足");
            }

            Long adminId = Long.valueOf(params.get("adminId").toString());

            // 不能重置自己的密码
            if (adminId.equals(tokenInfo.getAdminId())) {
                return Result.error(400, "不能重置自己的密码");
            }

            boolean success = adminService.resetPassword(adminId, tokenInfo.getAdminId());
            if (success) {
                return Result.success("密码重置成功，默认密码为：123456");
            } else {
                return Result.error("密码重置失败");
            }

        } catch (Exception e) {
            log.error("重置管理员密码异常", e);
            return Result.error("重置管理员密码失败");
        }
    }

    /**
     * 密码加密
     */
    private String encryptPassword(String password) {
        return DigestUtils.md5DigestAsHex((password + "campus-help-admin-salt").getBytes());
    }
}
